package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.*;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkJoinGroupByProto;
import com.sencorsta.ids.talk.proto.ImtalkPushGroupUpdateMsg;
import com.sencorsta.ids.talk.proto.ImtalkPushMessageByProto;
import com.sencorsta.utils.date.DateUtil;
import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author TAO
 * @description:邀请加入群聊
 * @date 2019/6/20 14:04
 */

@ClientEvent("JoinGroup")
public class JoinGroupHandler extends OpenMessageHandler implements RedisService {
    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.debug("--------------------------------邀请加入群JoinGroup----------------------------------");

        ImtalkJoinGroupByProto.JoinGroupRes.Builder res = ImtalkJoinGroupByProto.JoinGroupRes.newBuilder();


        //服务器推的群状态跟新
        ImtalkPushGroupUpdateMsg.PushGroupUpdate.Builder pushUpdate = ImtalkPushGroupUpdateMsg.PushGroupUpdate.newBuilder();

        //服务器推送的消息
        ImtalkPushMessageByProto.PushMsg.Builder pushsys = ImtalkPushMessageByProto.PushMsg.newBuilder();
        try {
            ImtalkJoinGroupByProto.JoinGroupReq req = ImtalkJoinGroupByProto.JoinGroupReq.parseFrom(protobuf);
            res.setSign(req.getSign());//前后端消息标识

            //群id
            String groupId = req.getGroupId();

            Out.debug("groupId===>" + groupId);

            //得到邀请的好友列表
            List<String> list = req.getFriendListList();

            //得到当前群成员列表
            Set<String> groupMemberList = R_GROUP.hkeys(groupId);

            //剔除已存在的群成员
            List<String> lists = new ArrayList<String>();
            for (var item : list) {
                if (!groupMemberList.contains(item)) {
                    lists.add(item);
                }
            }
            list = lists;


            //权限判断--判断发起邀请者的权限
            JSONObject member = JSONObject.parseObject((R_GROUP.hget(groupId, userId)));
            String adminType = String.valueOf(member.get("adminType"));
            Out.debug("当前的userId------------" + userId);
            Out.debug("当前人的权限---------" + adminType);
            if ("3".equals(adminType)) {
                Out.debug("返回权限不足");
                String invite = R_PROPERTY.hget(groupId, "invite");
                if (!"1".equals(invite)) {
                    return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.JURISDICTION_INSUFFICIENT)));//返回权限不足
                }
            }


            //通过群id找到群---将目标用户添加到群里

            JSONObject siro = new JSONObject();//权限列表对象
            siro.put("adminType", 3);//这里1代表是   1.群主  2.管理员 3平民
            siro.put("silent", 1);//后期直接用对接key匹配    3.禁言
            siro.put("nickname", "");//                      4.在本群的昵称

            for (String l : list) {
                siro.put("nickname", R_USER.hget(l, "nickname"));
                //通过邀请的好友的id得到用户的头像
                R_GROUP.hset(groupId, l, String.valueOf(siro));//设置群成员权限
            }


            int count = Integer.parseInt(R_PROPERTY.hget(groupId, "count")) + list.size();
            Out.trace(count);

            R_PROPERTY.hset(groupId, "count", String.valueOf(count));

            //得到整个群成员列表 TODO 注意这个memberList
            Object[] memberList = R_GROUP.hkeys(groupId).toArray();
            //发出更新群的操作
            pushUpdate.setGroupId(groupId);//群聊id
            //循环群列表给每个接收者发送更新
            for (Object receiver : memberList) {
                MsgService.pushAndSavedUnique((pushProto(String.valueOf(receiver), "push.groupUpdate", pushUpdate)), "push.groupUpdate-" + receiver);
            }

            // 推送给加入群验证消息给目标用户
            //定义系统消息
            JSONObject msg = new JSONObject();
            msg.put("srcId", "0");
            //获取目标用户id
            msg.put("tagId", groupId);
            //获取消息内容
            msg.put("msgContent", "欢迎加入群聊，现在可以聊天了");
            //内容类型 1.文字 2.图片  等等...--0.系统消息
            msg.put("msgType", 1007);
            //获取消息类型1.单发  2.群发
            msg.put("tagType", 2);
            //消息时间
            msg.put("time", DateUtil.getDateTime());
            //添加Redis的消息库中
            String msgId = IdService.newMsgId();
            R_MESSAGES.set(msgId, msg.toJSONString());

            pushsys.setUserId(groupId);
            pushsys.setMsgId(msgId);

            AuroraPush.pushAurora(msgId);//极光推送
            //系统推送消息
            for (Object receiver : memberList) {
                MsgService.pushAndSaved(pushProto(String.valueOf(receiver), "push.Msg", pushsys));
            }


            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }


}
